package com.cloudcc.mobile.view.im;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.cloudcc.cloudframe.adapter.ViewHolder;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.CoworkerListAdapter;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.event.CoworkerEventList.CoworkerListEvent;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.main.fragment.CoworkerListFragment;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;

/** 
* @Description: 群组选择联系人 
* @author wangzhiqiang
* @date 2016-1-14 下午1:53:35 
*  
*/
public class GroupPickFragment extends CoworkerListFragment {

	/** 是否为一个新建的群组 */
	protected boolean isCreatingNewGroup;
	/** 是否为单选 */
	private boolean isSignleChecked;
	/** group中一开始就有的成员 */
	private List<String> exitingMembers;
	private String groupName;
	private String groupId;
	@Override
	public void init() {
		super.init();
		
		initArg();
		
		if (groupId == null) {// 创建群组
			isCreatingNewGroup = true;
		} else {
			// 获取此群组的成员列表
			EMGroup group = EMGroupManager.getInstance().getGroup(groupId);
			exitingMembers = group.getMembers();
		}
		//[005201576751721ufptn2010000000050855wyhh, 005201511668834zvq432010000000050855wyhh, 00520159411661123fi62010000000050855wyhh, 005201570227360lsuhv2010000000050855wyhh]
		// 005201301193416acljg2010000000050855wyhh
		//005201511668834zvq432010000000050855wyhh
		if(exitingMembers == null)
			exitingMembers = new ArrayList<String>();
		mLoadMoreLayout.setEnabled(false);
		headerbar.setLeftImageResource(R.drawable.ease_mm_title_back);
		headerbar.setTitle("请选择联系人");
		headerbar.setRightText("保存");
	}
	
	private void initArg(){
		Bundle bundle = getArguments();
		if (bundle!=null) {
			groupName = bundle.getString("groupName");
			groupId = bundle.getString("groupId");
		}
	}
	
	
	public void onEventMainThread(CoworkerListEvent event){
		headerbar.completeProgress();
		mRefreshLayout.refreshComplete();
		if (event.isError()) {
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		refreshData(event.getData());
	}
	
	protected void refreshData(List<CoworkerEntity> data){
		if (mAdapter == null) {
			mAdapter = new MySubListAdapter(mContext);
			mListView.setAdapter(mAdapter);
		}
		if (isFromRefresh()) {
			mContactes.clear();
			mContactes.addAll(data);
			mAdapter.changeData(data);
		} else {
			mContactes.addAll(data);
			mAdapter.addData(data);
		}
	}
	private List<String> checkIds =new ArrayList<String>();
	private class MySubListAdapter extends CoworkerListAdapter{
		
		public List<String> getToBeAddMembers(){
			return checkIds;
		}
		public MySubListAdapter(Context mContext) {
			super(mContext);
		}
		@Override
		public void convert(ViewHolder holder, CoworkerEntity t) {
			ImageView ivLogo = holder.getView(R.id.contact_item_name);
			String uri = UrlTools.getTopImage(t.getId());
			int colorindex=holder.getPostion()%colors.length;
			UserUtils.setLogoRound(uri, ivLogo, colors[colorindex], t.getNickRowName(), mContext);
			holder.setText(R.id.contact_item_logo, t.getName());
			CheckBox cbCheckBox = holder.getView(R.id.checkbox);
			if (hasInExit(t.getHxusername())) {
				cbCheckBox.setButtonDrawable(R.drawable.em_checkbox_bg_gray_selector);
				cbCheckBox.setOnCheckedChangeListener(null);
				cbCheckBox.setChecked(true);
			}else{
				cbCheckBox.setButtonDrawable(R.drawable.em_checkbox_bg_selector);
				cbCheckBox.setOnCheckedChangeListener(null);
				cbCheckBox.setChecked(false);
				
				if (hasInChecked(t.getHxusername())) {
					cbCheckBox.setChecked(true);
				}else{
					cbCheckBox.setChecked(false);
				}
				final String userHxName =t.getHxusername();
				cbCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						if (hasInChecked(userHxName)) {
							checkIds.remove(userHxName);
						}else{
							checkIds.add(userHxName);
						}
					}
				});
			}
		}
		private boolean hasInExit(String username){
			for (String exiting : exitingMembers) {
				if (StringUtils.equals(username.trim(), exiting)) {
					return true;
				}
			}
			return false;
		}
		
		private boolean hasInChecked(String userName){
			StringBuilder sb = new StringBuilder();
			sb.append("当前人员：");
			for (String  username: checkIds) {
				sb.append(username);
				sb.append("#");
			}
			System.out.println(sb.toString());
			return checkIds.contains(userName);
		}
		
		
		@Override
		public int getLayoutId() {
			return R.layout.contact_list_select;
		}
		
	}
	
	/**
	 * 确认选择的members
	 * 
	 * @param v
	 */
	public void save(View v) {
		LogUtils.d("imchat", "新增成员个数:"+checkIds.size());
		getActivity().setResult(Activity.RESULT_OK, new Intent().putExtra("newmembers", ((MySubListAdapter)mAdapter).getToBeAddMembers().toArray(new String[0])));
		getActivity().finish();
	}
	@Override
	public void onClickRight(View v) {
		save(v);
	}
	
	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}
}
